package org.mj.im.server.runner;

import jakarta.annotation.PreDestroy;
import org.mj.im.server.netty.IMNettyServer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
public class IMServerRunner implements CommandLineRunner {

    private final List<IMNettyServer> imNettyServer;

    public IMServerRunner(List<IMNettyServer> imNettyServer) {
        this.imNettyServer = imNettyServer;
    }

    @Override
    public void run(String... args) throws Exception {
        if (CollectionUtils.isEmpty(imNettyServer)){
            return;
        }
        imNettyServer.forEach(IMNettyServer::start);
    }

    public boolean ready(){
        if (CollectionUtils.isEmpty(imNettyServer)){
            return false;
        }
        return imNettyServer.stream().allMatch(IMNettyServer::ready);
    }

    @PreDestroy
    public void destroy(){
        if (CollectionUtils.isEmpty(imNettyServer)){
            return;
        }
        imNettyServer.forEach(IMNettyServer::stop);
    }
}
